package com.rain.rainspringboot3.encryption.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rain.rainspringboot3.encryption.entity.SensitiveData;
import com.rain.rainspringboot3.encryption.mapper.SensitiveDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * @author rain
 */
@Service
@Slf4j
public class SensitiveDataServiceImpl implements SensitiveDataService {

    @Autowired
    @Lazy
    private SensitiveDataMapper sensitiveDataMapper;

    @Autowired
    @Lazy
    private EncryptionService encryptionService;

    @Override
    public boolean saveData(SensitiveData sensitiveData) {
        return sensitiveDataMapper.insert(sensitiveData) > 0;
    }

    @Override
    public SensitiveData getByCipherText(String cipherText) {
        try {
            LambdaQueryWrapper<SensitiveData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SensitiveData::getCipherText, cipherText);
            return sensitiveDataMapper.selectOne(wrapper);
        } catch (Exception e) {
            log.error("查询敏感数据异常", e);
            return null;
        }
    }

    @Override
    public SensitiveData getById(Long sensitiveDataId) {
        return sensitiveDataMapper.selectById(sensitiveDataId);
    }

    @Override
    public SensitiveData getByPrefixAndSuffixAndCipherText(String prefix, String suffix, String plainText) {
        try {
            if (StringUtils.isBlank(plainText) || StringUtils.isBlank(prefix)) {
                return null;
            }
            LambdaQueryWrapper<SensitiveData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SensitiveData::getPrefix, prefix);
            wrapper.eq(SensitiveData::getSuffix, suffix);
            List<SensitiveData> sensitiveDataList = sensitiveDataMapper.selectList(wrapper);
            if (sensitiveDataList.size() == 1) {
                return sensitiveDataList.get(0);
            } else {
                for (SensitiveData sensitiveData : sensitiveDataList) {
                    String dbPlainText = encryptionService.getPlainText(sensitiveData);
                    if (Objects.equals(plainText, dbPlainText)) {
                        return sensitiveData;
                    }
                }
            }
            return sensitiveDataMapper.selectOne(wrapper);
        } catch (Exception e) {
            log.error("查询敏感数据异常", e);
            return null;
        }
    }
}
